//此版本为Linux环境下的启动线程，不同环境的线程库是不一样的
//由于pthread库不是Linux系统默认的库，连接时需要使用库libpthread.a,所以在使用pthread_create创建线程时，在编译中要加-lpthread参数
//编译命令  gcc ThreadOperations.c  -lpthread -o ThreadOperations
#include <stdio.h>
#include <pthread.h>
#include <math.h> 

#define thread_count 5										//Number of task threads


pthread_t thread_id[thread_count];							//Array of thread identifiers
size_t task = 0;											//Integer identifying a task
struct timespec duration = {.tv_sec=1,.tv_nsec=0};			//Task work period
// mtx_t task_mtx;											//Mutex for access to task

pthread_mutex_t seq_lock = PTHREAD_MUTEX_INITIALIZER;  

//Function to carry out task
int execute_task(void *arg){
	// mtx_lock(&task_mtx);
    pthread_mutex_lock(&seq_lock);  
	size_t local_task = ++task;
    pthread_mutex_unlock(&seq_lock);  
	// mtx_unlock(&task_mtx);

	printf("Task %zd started.\n", local_task);
	// pthread_sleep(&duration,NULL);						//Just to make things take longer.
	sleep(1);
	double x = 0;
	for(int i=0;i<1000000000;++i)
		x = sqrt(3.1415926);

	printf("Task %zd finished\n",local_task );
	return 0;
}

int main(int argc, char const *argv[])
{	

	//Create the threads to carry out the tasks concurrently
	for (size_t i = 0; i < thread_count; ++i)
	{
		int err;
		if((err == pthread_create(&thread_id[i],NULL,execute_task,NULL))){
			fprintf(stderr,"Thread creation failed.\n");
			pthread_exit(-1);
		}
	}

	//Join the additional threads to the main thread
	for(size_t j=0;j<thread_count;j++)
		pthread_join(thread_id[j],NULL);

	return 0;
}